<template>
  <div class="container" ref="el"></div>
</template>
<script>
import * as echarts from 'echarts'
import { getKDataApi } from '@/api/data';

const option = {
  title: {
    text: '商品类别销量图'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['电子产品', '服装首饰', '文具办公', '汽车用品']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: []
};

export default {
  name: 'MainChartItem',
  data () {
    return {
      chartData: null
    }
  },
  methods: {
    handleGetKData () {
      getKDataApi().then(res => {
        this.chartData = res
      })
    }
  },
  watch: {
    chartData: {
      handler () {
        option.xAxis.data = this.chartData.x
        option.series = []
        option.legend.data.forEach((item, index) => {
          option.series.push({
            name: item,
            type: 'line',
            stack: 'Total',
            data: this.chartData.val[index]
          })
        })

        option && this.chartIns.setOption(option)
      }
    }
  },
  mounted () {
    this.handleGetKData()
    this.chartIns = echarts.init(this.$refs.el);
    option && this.chartIns.setOption(option)
  }
}
</script>
<style scoped>
.container {
  width: 100%;
  height: 400px;
}
</style>
